package ru.lukyanets.transmission.client.ui.window;

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import ru.lukyanets.transmission.client.action.ConnectAction;
import ru.lukyanets.transmission.client.action.ExitAction;
import ru.lukyanets.transmission.client.app.FxControllerFactory;
import ru.lukyanets.transmission.client.app.PrimaryStage;
import ru.lukyanets.transmission.client.config.GUIConfig;
import ru.lukyanets.transmission.client.util.LocalizationUtil;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.ResourceBundle;

/**
 * @author slukyanets
 */
@Singleton
public final class MainWindow {
    private static final String ROOT_NODE = "/fxml/application.fxml";
    private static final String APP_ICON = "/img/icon/32x32.png";

    @Inject
    public MainWindow(FxControllerFactory controllerFactory,
                      @PrimaryStage Stage primaryStage,
                      GUIConfig guiConfig,
                      ConnectAction connectAction,
                      ExitAction exitAction) throws IOException {
        LocalizationUtil.setLocale(guiConfig.getLocale());

        ResourceBundle bundle = LocalizationUtil.getResourceBundle();
        FXMLLoader loader = new FXMLLoader(getClass().getResource(ROOT_NODE), bundle);
        loader.setControllerFactory(controllerFactory);
        Parent root = loader.load();

        Scene app = new Scene(root, guiConfig.getWindowSize().getWidth(), guiConfig.getWindowSize().getHeight());

        primaryStage.setTitle(bundle.getString("application.name"));
        primaryStage.setScene(app);
        primaryStage.setMinHeight(GUIConfig.MIN_HEIGHT);
        primaryStage.setMinWidth(GUIConfig.MIN_WIDTH);
        primaryStage.setMaximized(guiConfig.isMaximized());
        //noinspection DataFlowIssue
        primaryStage.getIcons().addAll(new Image(getClass().getResourceAsStream(APP_ICON)));
        primaryStage.show();

        connectAction.handle(new ActionEvent());

        app.getWindow().setOnCloseRequest(event -> {
            event.consume();
            exitAction.handle(new ActionEvent(event.getSource(), event.getTarget()));
        });
    }
}
